package com.yangguang.huahui.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.yangguang.huahui.R;
import com.yangguang.huahui.easemob.AppHelper;
import com.yangguang.huahui.ui.activitys.BaseActivity;
import com.yangguang.huahui.ui.activitys.FriendsActivity;
import com.yangguang.huahui.ui.adapters.TypePageAdapter;
import com.yangguang.huahui.utils.LogUtil;
import com.yangguang.huahui.utils.RxBus;
import com.yangguang.huahui.widget.BadgeView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.badgeview.BGABadgeView;

/**
 * Created by Administrator on 2017/3/2.
 */

public class MessageFragment extends BaseFragment implements TabLayout.OnTabSelectedListener {
    public static MessageFragment newInstance(String type) {
        MessageFragment fragment = new MessageFragment();
        Bundle arguments = new Bundle();
        arguments.putString("type", type);
        fragment.setArguments(arguments);
        return fragment;
    }

    @BindView(R.id.mViewPager)
    ViewPager mViewPager;
    @BindView(R.id.mTabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.tv_dot)
    TextView tv_dot;

    private List<BaseFragment> mFragments = new ArrayList<>();
    private List<String> mTitles = new ArrayList<>();
    private TypePageAdapter mTypeAdapter;

    ChatMessageFragment chatMessageFragment = new ChatMessageFragment();

    //接收消息监听
    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                AppHelper.getInstance().getNotifier().onNewMsg(message);
            }
            otherHandler.postDelayed(otherRunnable, 0);
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };


    private Handler otherHandler = new Handler();
    private Runnable otherRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                setDot(tv_dot, EMClient.getInstance().chatManager().getUnreadMessageCount());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @OnClick({R.id.tv_friend})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_friend:
                startActivity(new Intent(mActivity, FriendsActivity.class));
                break;
        }
    }

    @Override
    protected int initLayoutId() {
        return R.layout.index_message;
    }

    @Override
    protected void initView() {
        mTabLayout.removeAllTabs();
        mTitles.clear();
        mFragments.clear();
        mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.feedback_message)));
        mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.chat_message)));
        mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.system_message)));
        mTitles.add(getString(R.string.feedback_message));
        mTitles.add(getString(R.string.chat_message));
        mTitles.add(getString(R.string.system_message));
        mFragments.add(FeedbackMessageFragment.newInstance(2));
        mFragments.add(chatMessageFragment);
        mFragments.add(new SystemMessageFragment());
        setPagerAdapter(mFragments, mTitles);
    }


    public void resume() {
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        otherHandler.postDelayed(otherRunnable, 100);
    }

    private void setDot(TextView tv_dot, int num) {
        if (num > 0) {
            tv_dot.setText(num + "");
            if (num > 99) {
                tv_dot.setText("99+");
            }
            tv_dot.setVisibility(View.VISIBLE);
        } else {
            tv_dot.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        switch (mTabLayout.getSelectedTabPosition()) {
            case 0:
                break;
            case 1:
                otherHandler.postDelayed(otherRunnable, 0);
                chatMessageFragment.fetchData();
                break;
            case 2:
                break;
        }
    }

    @Override
    protected void initData() {
        resume();
    }

    private void setPagerAdapter(List<BaseFragment> mFragments, List<String> mTitles) {
        mTypeAdapter = new TypePageAdapter(getChildFragmentManager());
        mTypeAdapter.setData(mFragments, mTitles);
        mViewPager.setAdapter(mTypeAdapter);
        mViewPager.setOffscreenPageLimit(mTitles.size() - 1);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabsFromPagerAdapter(mTypeAdapter);
        mTabLayout.addOnTabSelectedListener(this);
        mViewPager.setCurrentItem(1);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (tab.getPosition() == 0) {
            setIdentity((BaseActivity) getActivity());
        }
        mViewPager.setCurrentItem(tab.getPosition());
    }

    private void setIdentity(final BaseActivity baseActivity) {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_feed_type, null);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_title);
        tv_title.setText(getString(R.string.feed_type));
        contentView.findViewById(R.id.tv_purchase).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RxBus.getInstance().post(1);
                baseActivity.alertDialog.dismiss();
            }
        });
        contentView.findViewById(R.id.tv_supply).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RxBus.getInstance().post(2);
                baseActivity.alertDialog.dismiss();
            }
        });
        baseActivity.show_bottom_dialog(contentView);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        if (tab.getPosition() == 0) {
            setIdentity((BaseActivity) getActivity());
        }
    }
}
